#pragma once
#include "datamanager.hpp"
#include <unistd.h>

namespace Cloud
{
    const useconds_t sleepTime = 2000000; // 每次两秒
    class HotFileManager
    {
    public:
        bool isHotFile(const std::string &filePath)
        {                
            size_t aTime = FileUtils(filePath).getATime();
            size_t mTime = FileUtils(filePath).getMTime();
            size_t t = aTime > mTime ? aTime : mTime;
            size_t hotTime = Config::getInstance()->getHotTime();
            size_t curTime = time(nullptr);
            std::cout << filePath << ": " << curTime << ' ' << t << ' ' << hotTime << std::endl;
            return curTime - t < hotTime;
        }
        void run()
        {
            while (1)
            {
                std::vector<std::string> pathes;
                FileUtils(Config::getInstance()->getBackDir()).scanDirectory(&pathes); // 这里只扫描 /backdir/
                for (const auto &path : pathes)
                {
                    if (isHotFile(path))
                        continue;
                    packFile(path);
                }
                usleep(sleepTime);
            }
        }
        void packFile(const std::string &path)
        {
            std::cout << "begin packFile\n";
            std::string lhs = Config::getInstance()->getPackDir(),        // 添加 /packdir/前缀
                        name = FileUtils(path).getFileName(),             // 去掉 /backdir/前缀
                        rhs = Config::getInstance()->getPackfileSuffix(), // 添加 .lz 后缀
                        dst = lhs + name + rhs;
            FileUtils(path).compress(dst);

            // 先改信息：
            FileInfo fi(path);
            fi._isPacked = true;
            // 再remove：
            FileUtils(path).remove();
            // 再保存：
            DataManager::getInstance()->update(fi);
            std::cout << "packed success: " << dst << std::endl;
            // 注：等它真的压缩了再更新信息,
            // 不能为了表示要更新信息, 就把update放函数开头。
        }
    };
}